Completed
Push — develop ( d51c0f...98f175 )
by Xaver
01:35
created

math.js ➔ ... ➔ distance   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
nc 1
dl 0
loc 3
rs 10
nop 2
1
define(function () {
2
  return {
3
    distance: function distance(a, b) {
4
      return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
5
    },
6
7
    distancePoint: function distancePoint(a, b) {
8
      return Math.sqrt(distance(a, b));
9
    },
10
11
    distanceLink: function distanceLink(p, a, b) {
12
      /* http://stackoverflow.com/questions/849211 */
13
      var l2 = distance(a, b);
14
      if (l2 === 0) {
15
        return distance(p, a);
16
      }
17
      var t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
18
      if (t < 0) {
19
        return distance(p, a);
20
      } else if (t > 1) {
21
        return distance(p, b);
22
      }
23
      return distancePoint(p, {
24
        x: a.x + t * (b.x - a.x),
25
        y: a.y + t * (b.y - a.y)
26
      });
27
    }
28
  };
29
});
30